package com.woniuxy.sales.controller;

import com.woniuxy.sales.common.enumeration.BusinessCode;
import com.woniuxy.sales.model.entity.Categories;
import com.woniuxy.sales.model.vo.UsersVo;
import com.woniuxy.sales.service.CategoriesService;
import com.woniuxy.sales.service.UsersService;
import com.woniuxy.sales.untils.Assert;
import com.woniuxy.sales.untils.JwtTemplate;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/carType")
@Slf4j
public class CategoriesController {
    @Autowired
    private CategoriesService categoriesService;
    @Autowired
    private JwtTemplate jwtTemplate;

    @GetMapping("/findAll")
    @ApiOperation("查询所有分类")
    public ResponseEntity<List<Categories>> findAll() {
        List<Categories> types = categoriesService.findAll();
        return ResponseEntity.ok(types);
    }

    @GetMapping("/isLogged")
    @ApiOperation("判断用户是否登录")
    public ResponseEntity<?> isLogged(@RequestHeader(required = false, name = "Authorization") String authorization) {
        log.info("用户请求头中携带的Token是：{}", authorization);
        //如果为空表示没有登录
        Assert.error(StringUtils.isEmpty(authorization), BusinessCode.USER_NOT_LOGGED);
        //判断Token是否有效
        boolean isValid = jwtTemplate.validateToken(authorization);
        Assert.error(!isValid, BusinessCode.INVALID_TOKEN);
        //获取用户的ID
        Long userId = Long.valueOf(jwtTemplate.getValue(authorization, "userId"));
        //调用业务层查询用户是否存在
        UsersVo user = categoriesService.findByUserId(userId);
        log.info("获取到的用户是：｛｝",user);
        Assert.error(user == null, BusinessCode.USER_NOT_EXIST);
        return ResponseEntity.ok(user);
    }
    @GetMapping("/findById")
    @ApiOperation("根据ID查询")
    public ResponseEntity<Categories> findById(@RequestParam("id") Long Id) {
        Categories carType = categoriesService.findById(Id);
        return ResponseEntity.ok(carType);
    }

}
